package org.edu.modules.oa.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.apache.shiro.SecurityUtils;
import org.edu.common.api.vo.Result;
import org.edu.common.aspect.annotation.AutoLog;
import org.edu.common.system.vo.LoginUser;
import org.edu.common.util.RedisUtil;
import org.edu.modules.oa.config.QueryConditionTool;
import org.edu.modules.oa.entity.VeOaCarInfoEntity;
import org.edu.modules.oa.entity.VeOaCarShiYongEntity;
import org.edu.modules.oa.service.IVeOaCarShiYongService;
import org.edu.modules.oa.util.OssDownloadUtil;
import org.edu.modules.oa.vo.QueryCondition;
import org.edu.modules.oa.vo.VeOaCarInfoTableVo;
import org.edu.modules.oa.vo.VeOaCarShiYongExcelVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

//@Api(tags="车辆保险业务")
@Api(tags="车辆使用记录")
@RestController
@RequestMapping("oa/vehicleEmploy")
@Slf4j
public class VeOaCarShiYongController {

    @Resource
    private IVeOaCarShiYongService veOaCarShiYongService;
    @Autowired
    private RedisUtil redisUtil; // redis服务类

    @ApiOperation(value = "按页面和条件查看车辆使用记录")
    //加载车辆使用界面表格
    @PostMapping("/loadTable")
    public Result<?> loadTable(Integer current, Integer pageSize, VeOaCarShiYongEntity veOaCarShiYongEntity){
        HashMap<String,Object> map = veOaCarShiYongService.loadTable(current,pageSize,veOaCarShiYongEntity);
        return Result.OK(map);
    }

    //删除一条使用记录
    @ApiOperation(value = "删除一条车辆使用记录")
    @PostMapping("/deleteEmplotyById")
    public Result<?> deleteEmplotyById(Integer id){
        int res = veOaCarShiYongService.deleteEmplotyById(id);
        if(res == 0){
            return Result.error(500,"删除失败了");
        }
        return Result.OK();
    }

    @ApiOperation(value = "批量删除车辆使用记录")
    @PostMapping("/deleteEmplotyAll")
    public Result<?> deleteEmplotyAll(String ids){
        String [] arr = ids.split(",");
        for(String id : arr){
            if(null != id && !id.equals("") && id != "") {
                veOaCarShiYongService.deleteEmplotyById(Integer.parseInt(id));
            }
        }
        return Result.OK();
    }
    @ApiOperation(value = "查看全部车辆的id和名称")
    @PostMapping("/selectCarAll")
    public Result<?> selectCarAll(){
        List list = veOaCarShiYongService.selectCarAll();
        return Result.OK(list);
    }
    @ApiOperation(value = "修改车辆使用记录")
    @PostMapping("/setEmplotyById")
    public Result<?> setEmplotyById(VeOaCarShiYongEntity v,String sTime,String eTime) throws ParseException {
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        v.setStartTime(formatter.parse(sTime.trim()));
        v.setEndTime(formatter.parse(eTime.trim()));
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        v.setUpdateBy(user.getId());
        v.setUpdateName(user.getRealname());
        int res = veOaCarShiYongService.setEmplotyById(v);
        if(res == 0){
            return Result.error(500,"添加失败了");
        }
        return Result.OK();
    }

    @ApiOperation(value = "添加车辆使用记录")
    @PostMapping("/addEmploty")
    public Result<?> addEmploty(VeOaCarShiYongEntity v,String sTime,String eTime) throws ParseException{
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        v.setStartTime(formatter.parse(sTime.trim()));
        v.setEndTime(formatter.parse(eTime.trim()));
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        v.setCreateBy(user.getId());
        v.setCreateName(user.getRealname());
        int res = veOaCarShiYongService.addEmploty(v);
        if(res == 0){
            return Result.error(500,"添加失败");
        }
        return Result.OK();
    }

    @ApiOperation(value = "车辆导出功能")
    @GetMapping(value = "exportEmploty")
    public ModelAndView exportEmploty(){
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //获取需要导出的Excel数据的集合
        List<VeOaCarShiYongEntity> list = veOaCarShiYongService.selectAllEmploty();
        //创建一个导出用的集合
        List<VeOaCarShiYongExcelVo> excelVoList = new ArrayList<>();
        for (VeOaCarShiYongEntity v : list) {
            VeOaCarShiYongExcelVo excelVo = new VeOaCarShiYongExcelVo();
            excelVo.setCarName(v.getCarName());
            excelVo.setDriverUser(v.getDriverUser());
            excelVo.setYongcheUser(v.getYongcheUser());
            excelVo.setYongcheDep(v.getYongcheDep());
            //把时间类型改成展示的正常的时间类型
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            excelVo.setStartTime(formatter.format(v.getStartTime()));
            excelVo.setEndTime(formatter.format(v.getEndTime()));
            excelVo.setDestination(v.getDestination());
// 李少君           excelVo.setChufalichengshu(v.getChufalichengshu());
// 李少君          excelVo.setDaodaLichengshu(v.getDaodaLichengshu());
            excelVo.setHejiLichengshu(v.getHejiLichengshu());
            excelVo.setYouhaoshu(v.getYouhaoshu());
// 李少君           excelVo.setDiaoduUser(v.getDiaoduUser());
// 李少君           excelVo.setShiYong(v.getShiYong());
// 李少君           excelVo.setBackInfo(v.getBackInfo());
            excelVoList.add(excelVo);
        }
        //文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆使用记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarShiYongExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //表格头部
        ExportParams exportParams = new ExportParams("车辆使用记录", "导出人:"+user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelVoList);
        return mv;
    }

    @ApiOperation(value = "车辆使用记录导出模板")
    @GetMapping(value = "exportList")
    public ModelAndView exportList(){
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        List<VeOaCarShiYongExcelVo> excelVoList = new ArrayList<>();
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆使用记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarShiYongExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //表格头部
        ExportParams exportParams = new ExportParams("车辆使用记录", "导出人:"+user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelVoList);
        return mv;
    }

    @ApiOperation(value = "车辆使用记录导入")
    @PostMapping(value = "importExcel")
    public Result<?> importExcel(HttpServletRequest req, HttpServletResponse resp){
        System.out.println("准备开始导入");
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Integer count = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()){
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            //获取上传的表格内的数据的集合
            try {
                List<VeOaCarShiYongExcelVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarShiYongExcelVo.class, params);
                for (VeOaCarShiYongExcelVo e : list) {
                    System.out.println(e);
                }
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //添加数据库使用的集合
                List<VeOaCarShiYongEntity> entityList = new ArrayList<>();
                for (VeOaCarShiYongExcelVo vo : list) {
                    VeOaCarShiYongEntity veOaCarShiYongEntity = new VeOaCarShiYongEntity();
                    //查看车辆ID是否存在
                    if(vo.getCarName() != null){
                        count++;
                        System.out.println(vo);
                        VeOaCarInfoEntity veOaCarInfoEntity = veOaCarShiYongService.selectCarByName(vo.getCarName());
                        if(null != veOaCarInfoEntity){
                            veOaCarShiYongEntity.setCarId(veOaCarInfoEntity.getId());
                            veOaCarShiYongEntity.setCarName(veOaCarInfoEntity.getCarName());
                            veOaCarShiYongEntity.setDriverUser(vo.getDriverUser());
                            veOaCarShiYongEntity.setYongcheUser(vo.getYongcheUser());
                            veOaCarShiYongEntity.setYongcheDep(vo.getYongcheDep());
                            //把表格的时间改成data类型
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            veOaCarShiYongEntity.setStartTime(formatter.parse(vo.getStartTime()));
                            veOaCarShiYongEntity.setEndTime(formatter.parse(vo.getEndTime()));
                            veOaCarShiYongEntity.setDestination(vo.getDestination());
// 李少君                           veOaCarShiYongEntity.setChufalichengshu(vo.getChufalichengshu());
// 李少君                           veOaCarShiYongEntity.setDaodaLichengshu(vo.getDaodaLichengshu());
                            veOaCarShiYongEntity.setHejiLichengshu(vo.getHejiLichengshu());
                            veOaCarShiYongEntity.setYouhaoshu(vo.getYouhaoshu());
// 李少君                           veOaCarShiYongEntity.setDiaoduUser(vo.getDiaoduUser());
// 李少君                           veOaCarShiYongEntity.setShiYong(vo.getShiYong());
// 李少君                           veOaCarShiYongEntity.setBackInfo(vo.getBackInfo());
                            veOaCarShiYongEntity.setCreateBy(user.getId());
                            veOaCarShiYongEntity.setCreateName(user.getRealname());
                            veOaCarShiYongEntity.setTerminalId(1L);
                            System.out.println("-----------------------------------------");
                            System.out.println("即将导入的数据"+veOaCarShiYongEntity);
                            System.out.println("-----------------------------------------");
                            entityList.add(veOaCarShiYongEntity);
                            //--------------------------------添加未登记车辆无法导入提示（lbh）
                        }else {
                            return Result.ok("文件导入失败，第"+count+"条数据中车辆未登记，请重新检查。");
                        }
                        // ----------------------------------
                    }

                }
                System.out.println(entityList.size()+"导入记录长度");
                veOaCarShiYongService.saveBatch(entityList);
                return Result.ok("文件导入成功！数据行数：" + count);
            } catch (Exception e) {
                e.printStackTrace();
                return  Result.error("导入失败了");
            }finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
    @ApiOperation(value="高级搜索", notes="车辆使用记录-高级搜索")
    @PostMapping(value = "/queryEmploty")
    //@RequestBody String queryArray使用json的字符串来接收
    public Result<?> advancedQuery(@RequestBody String queryArray){
        //获取前台传过来的对象集合
        Map<String, List<QueryCondition>> maps = (Map<String, List<QueryCondition>>) JSON.parse(queryArray);
        List<QueryCondition> list=new ArrayList<QueryCondition>(JSONArray.parseArray(maps.get("queryArray").toString(),QueryCondition.class));
        String queryCondition="";
        String conditionStr =  QueryConditionTool.getQueryConditionTool().advancedQuery(list);
        conditionStr += "and is_deleted = '0'";
        HashMap<String,Object> map = veOaCarShiYongService.advancedQuery(conditionStr);
        return Result.OK(map);

    }

    @ApiOperation(value = "车辆导出功能")
    @GetMapping(value = "exportEmplotyById")
    public ModelAndView exportEmplotyById(){
        // 判断这辆车的导出
        VeOaCarInfoTableVo carInfo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //获取需要导出的Excel数据的集合
        List<VeOaCarShiYongEntity> list = veOaCarShiYongService.exportEmplotyById(carInfo.getId().intValue());
        //创建一个导出用的集合
        List<VeOaCarShiYongExcelVo> excelVoList = new ArrayList<>();
        for (VeOaCarShiYongEntity v : list) {
            VeOaCarShiYongExcelVo excelVo = new VeOaCarShiYongExcelVo();
            excelVo.setCarName(v.getCarName());
            excelVo.setDriverUser(v.getDriverUser());
            excelVo.setYongcheUser(v.getYongcheUser());
            excelVo.setYongcheDep(v.getYongcheDep());
            //把时间类型改成展示的正常的时间类型
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            excelVo.setStartTime(formatter.format(v.getStartTime()));
            excelVo.setEndTime(formatter.format(v.getEndTime()));
            excelVo.setDestination(v.getDestination());
// 李少君           excelVo.setChufalichengshu(v.getChufalichengshu());
// 李少君           excelVo.setDaodaLichengshu(v.getDaodaLichengshu());
            excelVo.setHejiLichengshu(v.getHejiLichengshu());
            excelVo.setYouhaoshu(v.getYouhaoshu());
// 李少君           excelVo.setDiaoduUser(v.getDiaoduUser());
// 李少君           excelVo.setShiYong(v.getShiYong());
// 李少君           excelVo.setBackInfo(v.getBackInfo());
            excelVoList.add(excelVo);
        }
        //文件名称
        mv.addObject(NormalExcelConstants.FILE_NAME, "车辆使用记录");
        mv.addObject(NormalExcelConstants.CLASS, VeOaCarShiYongExcelVo.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //表格头部
        ExportParams exportParams = new ExportParams("车辆使用记录", "导出人:"+user.getRealname(), "导出信息");
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, excelVoList);
        return mv;
    }

    @ApiOperation(value = "车辆使用记录导入")
    @PostMapping(value = "importExcelById")
    public Result<?> importExcelById(HttpServletRequest req, HttpServletResponse resp){
        VeOaCarInfoTableVo carInfo = (VeOaCarInfoTableVo) redisUtil.get("carInfo");
        //先把需要导入的文件上传
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) req;
        //获取上传的文件
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        Integer count = 0;
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()){
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            //获取上传的表格内的数据的集合
            try {
                List<VeOaCarShiYongExcelVo> list = ExcelImportUtil.importExcel(file.getInputStream(), VeOaCarShiYongExcelVo.class, params);
                // 获取redis存的用户值
                LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                //添加数据库使用的集合
                List<VeOaCarShiYongEntity> entityList = new ArrayList<>();
                for (VeOaCarShiYongExcelVo vo : list) {
                    VeOaCarShiYongEntity veOaCarShiYongEntity = new VeOaCarShiYongEntity();
                    //查看车辆ID是否存在
                    if(vo.getCarName() != null && vo.getId() == carInfo.getId()){
                        VeOaCarInfoEntity veOaCarInfoEntity = veOaCarShiYongService.selectCarByName(vo.getCarName());
                        if(null != veOaCarInfoEntity){
                            count++;
                            veOaCarShiYongEntity.setCarId(veOaCarInfoEntity.getId());
                            veOaCarShiYongEntity.setCarName(veOaCarInfoEntity.getCarName());
                            veOaCarShiYongEntity.setDriverUser(vo.getDriverUser());
                            veOaCarShiYongEntity.setYongcheUser(vo.getYongcheUser());
                            veOaCarShiYongEntity.setYongcheDep(vo.getYongcheDep());
                            //把表格的时间改成data类型
                            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            veOaCarShiYongEntity.setStartTime(formatter.parse(vo.getStartTime()));
                            veOaCarShiYongEntity.setEndTime(formatter.parse(vo.getEndTime()));
                            veOaCarShiYongEntity.setDestination(vo.getDestination());
// 李少君                           veOaCarShiYongEntity.setChufalichengshu(vo.getChufalichengshu());
// 李少君                           veOaCarShiYongEntity.setDaodaLichengshu(vo.getDaodaLichengshu());
                            veOaCarShiYongEntity.setHejiLichengshu(vo.getHejiLichengshu());
                            veOaCarShiYongEntity.setYouhaoshu(vo.getYouhaoshu());
// 李少君                           veOaCarShiYongEntity.setDiaoduUser(vo.getDiaoduUser());
// 李少君                           veOaCarShiYongEntity.setShiYong(vo.getShiYong());
// 李少君                           veOaCarShiYongEntity.setBackInfo(vo.getBackInfo());
                            veOaCarShiYongEntity.setCreateBy(user.getId());
                            veOaCarShiYongEntity.setCreateName(user.getRealname());
                            veOaCarShiYongEntity.setTerminalId(1L);
                            System.out.println("-----------------------------------------");
                            System.out.println(veOaCarShiYongEntity);
                            System.out.println("-----------------------------------------");
                            entityList.add(veOaCarShiYongEntity);
                        }
                    }
                }
                veOaCarShiYongService.saveBatch(entityList);
                return Result.ok("文件导入成功！数据行数：" + count);
            } catch (Exception e) {
                e.printStackTrace();
                return  Result.error("导入失败了");
            }finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    //获取模板下载地址
    @AutoLog(value = "公告新闻-模板地址获取")
    @ApiOperation(value = "模板地址", notes = "公告新闻-模板地址获取")
    @PostMapping(value = "/getUrl")
    public Result<T> getUrl() throws Exception {
        Result result = new Result();
        String url= OssDownloadUtil.getOssDownloadUtil().downFileFromOSS("车辆使用记模板.xls");
        result.success(url);
        return result;
    }



}
